﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YinfangWeb.BLL.Enum;
using YinfangWeb.BLL.Model;

namespace YinfangWeb.Common
{
    public class FileServer
    {
        private readonly string ftpHost = ConfigurationManager.AppSettings["FtpHost"];
        private readonly string ftpUser = ConfigurationManager.AppSettings["FtpUser"];
        private readonly string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"];
        private readonly string HttpFileBaseUrl = ConfigurationManager.AppSettings["HttpFileBaseUrl"];

        //创建商品图片上传文件夹-新增商品时调用
        public bool CreateDir(int spId)
        {
            bool result = true;
            //准备文件保存类型并初始化Ftp服务器
            var fileCategory = EnumFileType.Product;
            FtpHelper ftpHelper = new FtpHelper() { HostName = ftpHost, UserName = ftpUser, Password = ftpPassword };

            var folderName = $"{fileCategory.GetFolderName()}/{spId}";//原图目录
            if (result=ftpHelper.CreateDir(folderName))
            {
                folderName = $"{fileCategory.GetFolderName()}/{spId}/2";//850 x 850目录
                result= result && ftpHelper.CreateDir(folderName);
                folderName = $"{fileCategory.GetFolderName()}/{spId}/3";//3350 x 350目录
                result = result && ftpHelper.CreateDir(folderName);
                folderName = $"{fileCategory.GetFolderName()}/{spId}/4";//150 x 150目录
                result = result && ftpHelper.CreateDir(folderName);
                folderName = $"{fileCategory.GetFolderName()}/{spId}/5";//50 x 50目录
                result = result && ftpHelper.CreateDir(folderName);
            }
            return result;
        }

        //上传商品展示图片到Ftp服务器
        //50x50,350x350,850,原图
        public FileNameObj UploadSpDisplayMap(int spId, string fileName, byte[] fileData,EnumProductFile_ViewLogo viewLogo)
        {
            var result = new FileNameObj();
            //生成临时文件名
            var dotIndex = fileName.LastIndexOf(".");
            if (dotIndex <= 0)
            {
                return result;
            }
            var ext = fileName.Substring(dotIndex);
            var target = Guid.NewGuid().ToString("N") + ext;  //使用临时文件名

            //准备文件保存类型并初始化Ftp服务器
            var fileCategory = EnumFileType.Product;
            FtpHelper ftpHelper = new FtpHelper() { HostName = ftpHost, UserName = ftpUser, Password = ftpPassword };

            //保存原图
            var folderName = $"{fileCategory.GetFolderName()}/{spId}";
            var newFileName = ftpHelper.UploadSpFile(target, fileData, folderName);

            if (viewLogo == EnumProductFile_ViewLogo.Yes)//是展示图
            {
                //保存850x850
                folderName = $"{fileCategory.GetFolderName()}/{spId}/2";
                byte[] tempBuffer = ImageHelper.GetCutForSquare(fileData, 850, 50, ext);
                newFileName = ftpHelper.UploadSpFile(target, tempBuffer, folderName);

                ////保存350x350
                folderName = $"{fileCategory.GetFolderName()}/{spId}/3";
                tempBuffer = ImageHelper.GetCutForSquare(fileData, 350, 50, ext);
                newFileName = ftpHelper.UploadSpFile(target, tempBuffer, folderName);

                ////保存150x150
                folderName = $"{fileCategory.GetFolderName()}/{spId}/4";
                tempBuffer = ImageHelper.GetCutForSquare(fileData, 150, 50, ext);
                newFileName = ftpHelper.UploadSpFile(target, tempBuffer, folderName);

                ////保存50x50
                folderName = $"{fileCategory.GetFolderName()}/{spId}/5";
                tempBuffer = ImageHelper.GetCutForSquare(fileData, 50, 50, ext);
                newFileName = ftpHelper.UploadSpFile(target, tempBuffer, folderName);
            }
            //只返回新文件名，不带路径
            result.FileName = fileName;
            result.NewFileName = target;
            result.Url = $"{HttpFileBaseUrl}/{folderName}/{target}";
            return result;
        }

        //上传指定文件类型到Ftp服务器
        public string UploadTemp(string fileName, byte[] fileData)
        {
            return _Upload(fileName, fileData, EnumFileType.Temp);
        }
        private string _Upload(string fileName, byte[] fileData, EnumFileType fileCategory)
        {
            FtpHelper ftpHelper = new FtpHelper() { HostName = ftpHost, UserName = ftpUser, Password = ftpPassword };
            var folderName = $"{fileCategory.GetFolderName()}/{DateTime.Today.Year}";
            var newFileName = ftpHelper.UploadFile(fileName, fileData, folderName);
            return $"{HttpFileBaseUrl}/{folderName}/{newFileName}";
        }

        //从Ftp服务器删除商品的文件(一个商品文件有多个放在不同文件夹下)
        public bool DeleteSpFile(string id, string fileName, EnumProductFile_ViewLogo viewLogo)
        {
            FtpHelper ftpHelper = new FtpHelper() { HostName = ftpHost, UserName = ftpUser, Password = ftpPassword };
            //从Ftp服务器根目录开始的路径
            string filePath = "product/" + id + "/" + fileName;//原图
            ftpHelper.DeleteFile(filePath);
            if (viewLogo == EnumProductFile_ViewLogo.Yes)
            {
                filePath = "product/" + id + "/2/" + fileName;//850x850
                ftpHelper.DeleteFile(filePath);
                filePath = "product/" + id + "/3/" + fileName;//350x350
                ftpHelper.DeleteFile(filePath);
                filePath = "product/" + id + "/4/" + fileName;//150x150
                ftpHelper.DeleteFile(filePath);
                filePath = "product/" + id + "/5/" + fileName;//50x50
                ftpHelper.DeleteFile(filePath);
            }
            return true;
        }
        //文件保存在本机
        public IResult SaveFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(@"Z:\" + fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
                return new DataResult<dynamic>(new { url = "http://yf.401520.com/logo.png" });
            }
            finally
            {
                fs.Close();
                w.Close();
            }
        }
    }
}
